require 'json'
require 'cobravsmongoose'
require 'xml'
f=File.open("m.xml", "r")
content=f.read
f.close
myjson=CobraVsMongoose.xml_to_json(content)
puts myjson
p CobraVsMongoose.json_to_xml(myjson)
hasher=JSON.parse(myjson)
#p hasher
doc=XML::Document.new()
doc.root = XML::Node.new(hasher.keys[0])

hasher[hasher.keys[0]].each { |mainfield|
if !mainfield[1].kind_of?(Array)
  mainfield[1]=[mainfield[1]]
end
  #p mainfield[1]
  mainfield[1].each { |entry|
    doc.root << main_field=XML::Node.new(mainfield[0])
    entry.keys.each { |attribute|
    if attribute[0]=='@'
	XML::Attr.new(main_field, attribute[1..-1],entry[attribute])
    elsif attribute[0]=='$'
	main_field.content=entry[attribute]
    else
	subfield_element=entry[attribute]
	if !subfield_element.kind_of?(Array)
          subfield_element=[subfield_element]
	end
	subfield_element.each {|subfield_element|
	main_field << sub_field=XML::Node.new(attribute)
	subfield_element.keys.each { |attr|
	if attr[0]=='@'
	  XML::Attr.new(sub_field, attr[1..-1],subfield_element[attr])
	else
	  sub_field.content=subfield_element[attr]
	end
	  }
        }
    end         
    }
  }
}
#hasher[hasher.keys[0]].each {
# |mainfield| doc.root << data=XML::Node.new(mainfield[0])
#  p mainfield[1]
# mainfield[1].each { |entry| entry.keys.each { |attribute| 
#	XML::Attr.new(data, attribute[1..-1],mainfield[1][attribute]) if attribute[0]=='@'
#	data.content=mainfield[1][attribute] if attribute[0]=='$'
#	}
#}
#}
#p doc
